import { createRouter, createWebHashHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import type { Menu } from '@/api/auth/types'

const layout: RouteRecordRaw = {
    path: '/main',
    name: 'main',
    component: () => import('@/layout/index.vue'),
    children: []
} as RouteRecordRaw

const constantRoutes: RouteRecordRaw[] = [
    {
        path: '/',
        name: 'home',
        component: () => import('@/layout/index.vue')
    },
    layout,
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/login/login.vue')
    },
    {
        path: '/:pathMatch(.*)*',
        name: 'not-found',
        component: () => import('@/views/error/not-found.vue')
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes: constantRoutes
})

const modules = import.meta.glob('../views/**/*.vue')

export const appendRoutes = (menus: Menu[]) => {
    menus.forEach((menu) => {
        if (menu.path) {
            const path = `../views${menu.path}.vue`
            console.log('import view:', path)

            const viewComponent =  modules[path]

            const route: RouteRecordRaw = {
                path: menu.route,
                name: menu.id,
                component: viewComponent,
                // component: () => import(path)
            }
            // layout.children?.push(route)
            router.addRoute('home', route) // 将路由添加到 home 路由下
        }

        if (menu.children) {
            appendRoutes(menu.children)
        }
    })
}

export default router